<template>
  <div class="main">
    <el-form :model="formData" ref="form" label-width="120px" :rules="rules">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="formData.sort_order"  @change="handleChange" :min="1"/>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">确定保存</el-button>
        <el-button @click="reset">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addSpec,getSpecById,updateSpec } from '@/api/product.js'
export default {
  data(){
    return {
      formData:{
        name:'',
        sort_order:''
      },
      type:'add',
      rules:{
        name:[
          {
            required:true,
            message:'分类名称不能为空',
            trigger:'blur'
          }
        ]
      }
    }
  },
  mounted(){
    // 初始化分类
    
    this.init()
  },
  methods:{
    async init(){
      let id = this.$route.query.id
      console.log('id:',id)
      if(id){
        this.type = 'edit'
        let res = await getSpecById(id)
        if(res.code === 0){
          this.formData = res.data
        }else{
          this.$message({
            type:'error',
            message:'获取型号详情失败'
          })
        }
      }else{
        this.type = 'add'
      }
    },
    async submit(){
      // 添加型号
      this.$refs.form.validate(async(valid)=>{
        if(valid){
          if(this.type==='add'){
            let res = await addSpec(this.formData)
            if(res.code === 0){
              this.$message({
                type:'success',
                message:'新增型号成功'
              })
              this.$refs.form.resetFields()
            }else{
              this.$message({
                type:'error',
                message:'新增型号失败'
              })
            }
          }else{
            // 编辑
            let res = await updateSpec(this.formData)
            if(res.code === 0){
              this.$message({
                type:'success',
                message:'修改型号成功'
              })
              this.$refs.form.resetFields()
            }else{
              this.$message({
                type:'error',
                message:'修改型号失败'
              })
            }
          }
          
        }
      })
      
      
    },
    reset(){
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.main{
  .el-form{
    width: 500px;
    text-align: left;
  }
}
</style>

